import 'dart:async';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:photo_manager/photo_manager.dart'; // 使用 photo_manager 进行文件操作
import 'package:video_player/video_player.dart';
import 'package:wakelock/wakelock.dart';

import '/app/controllers/history_manager.dart';
import '/app/utils/time_utils.dart';
import '../home/home_controller.dart';

class PlayerController extends GetxController {
  HomeController countController = Get.find<HomeController>(); // 实例化控制器

  late VideoPlayerController videoPlayerController;
  var currentPosition = Duration.zero.obs; // 当前播放时间
  var totalDuration = Duration.zero.obs; // 视频总时长

  var isPlaying = false.obs;
  var isBuffering = false.obs;
  var isInitialized = false.obs; // 用于跟踪是否初始化完成
  var currentSpeed = 1.0.obs;
  var currentIndex = 0.obs;
  var videoName = "".obs;
  var isFullScreen = false.obs; // 用于表示全屏状态
  var isMuted = false.obs; // 用于表示是否静音
  List<AssetEntity> videoList = [];
  AssetEntity? currentVideo;

  var showControls = true.obs;

  Timer? _hideControlsTimer;

  @override
  void onInit() {
    super.onInit();
    Wakelock.enable(); // 防止播放时屏幕锁定
  }

  void updateCurrentPosition() {
    // 每次视频控制器更新时，获取当前的播放位置并更新
    videoPlayerController.addListener(() {
      currentPosition.value = videoPlayerController.value.position;
    });
  }

  @override
  void onClose() {
    if (videoPlayerController.value.isInitialized) {
      videoPlayerController.dispose();
    }
    Wakelock.disable(); // 退出时恢复屏幕锁定设置

    // 退出全屏
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: SystemUiOverlay.values);
    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);

    String videoId = currentVideo!.id;
    String lastPlayTime = TimeUtils.millisecondsToFormattedTime(getCurrentPosition());
    print("添加最近播放记录： " + videoId + ", 播放时间" + lastPlayTime);

    HistoryManager.addPlayHistory(videoId, lastPlayTime);
    print("添加最近播放记录： " + videoId + ", 播放时间" + lastPlayTime + "添加成功");

    super.onClose();
  }

  int getCurrentPosition() {
    return videoPlayerController.value.position.inMilliseconds;
  }

  // 初始化视频播放器
  Future<void> initializeVideo(AssetEntity video) async {
    isInitialized.value = false; // 初始化开始时设置为 false
    currentVideo = video;
    videoName.value = currentVideo?.title ?? '';
    final file = await video.file;
    if (file == null) return;

    videoPlayerController = VideoPlayerController.file(file)
      ..addListener(() {
        isPlaying.value = videoPlayerController.value.isPlaying;
        isBuffering.value = videoPlayerController.value.isBuffering;
        updateCurrentPosition(); // 初始化时开始监听播放时间
      });

    await videoPlayerController.initialize();

    // 初始化时设置总时长
    totalDuration.value = videoPlayerController.value.duration;

    isInitialized.value = true; // 初始化完成后设置为 true
    videoPlayerController.play();
  }

  // 播放/暂停切换
  void playPause() {
    if (videoPlayerController.value.isPlaying) {
      videoPlayerController.pause();
    } else {
      videoPlayerController.play();
    }
  }

  // 切换静音状态
  void toggleMute() {
    if (isMuted.value) {
      videoPlayerController.setVolume(1.0); // 恢复音量
    } else {
      videoPlayerController.setVolume(0.0); // 静音
    }
    isMuted.toggle(); // 切换静音状态
  }

  // 截图功能并保存到图库
  Future<void> captureScreenshot(GlobalKey videoKey) async {
    try {
      // 获取RenderRepaintBoundary对象
      RenderRepaintBoundary boundary = videoKey.currentContext!.findRenderObject() as RenderRepaintBoundary;

      // 生成图片数据
      ui.Image image = await boundary.toImage(pixelRatio: 2.0);
      ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
      if (byteData != null) {
        Uint8List pngBytes = byteData.buffer.asUint8List();

        // 检查权限
        final result = await PhotoManager.requestPermissionExtend();
        if (result.isAuth) {
          // 保存图片到相册
          final asset = await PhotoManager.editor.saveImage(pngBytes, filename: 'screenshot_' + DateTime.now().toString() + '.png');
          if (asset != null) {
            print("Screenshot saved successfully to gallery.");
          } else {
            print("Failed to save screenshot.");
          }
        } else {
          print("No permission to save image.");
        }
      }
    } catch (e) {
      print("Screenshot capture failed: $e");
    }
  }

  // 切换到下一个视频
  void seekToNext() {
    if (currentIndex.value < videoList.length - 1) {
      currentIndex.value++;
      initializeVideo(videoList[currentIndex.value]);
    }
  }

  // 切换到上一个视频
  void seekToPrevious() {
    if (currentIndex.value > 0) {
      currentIndex.value--;
      initializeVideo(videoList[currentIndex.value]);
    }
  }

  // 改变播放速度
  void changePlaybackSpeed(double? speed) {
    if (speed == null) return;
    currentSpeed.value = speed;
    videoPlayerController.setPlaybackSpeed(speed);
  }

  // 快进10秒
  void seekForward() {
    videoPlayerController.seekTo(videoPlayerController.value.position + Duration(seconds: 10));
  }

  // 快退10秒
  void seekBackward() {
    videoPlayerController.seekTo(videoPlayerController.value.position - Duration(seconds: 10));
  }

  // 全屏切换
  void toggleFullScreen() {
    if (isFullScreen.value) {
      // 退出全屏
      SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: SystemUiOverlay.values);
      SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
    } else {
      // 进入全屏
      SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
      SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeRight, DeviceOrientation.landscapeLeft]);
    }
    isFullScreen.toggle(); // 切换全屏状态
  }

  // 切换控件显示/隐藏的状态
  void toggleControls() {
    showControls.value = !showControls.value;
  }
}
